package ls.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Random;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import ls.model.Moaning;
import ls.repository.MoaningRepository;
import org.springframework.transaction.annotation.Transactional;

@Controller
@RequestMapping("/reset")
public class ResetController {
    
    @Autowired
    private MoaningRepository moaningRepository;
    
    @PersistenceContext
    private EntityManager entityManager;
    
    private Random random = new Random(System.currentTimeMillis());
    private static final String[] TEXT_LIST = {
        "The landlord doesn't want to pay the money he owes me",
        "I can''t understand what people are saying",
        "I''m scared of the customers",
        "i have too many things to do",
        "I'm slow in my work",
        "I feel I''m not doing enough at work",
        "I can't sleep at night",
        "I feel like I was tricked",
        "My customer is disappointed for all the mistakes that I''ve done lately",
        "Tonight I''m home alone, nobody to hang out with",
        "I waste a lot of time when I try to travel by train",
        "I need to stay until late to finish my work",
        "I'm the bottleneck of my team",
        "They put me to work on something marginal",
        "I feel guilty because I left the office earlier",
        "I'm full of bad thoughts",
    };

    @RequestMapping
    @Transactional
    public @ResponseBody String reset() throws IOException {
        entityManager.createQuery("DELETE FROM Moaning").executeUpdate();
        entityManager.createQuery("DELETE FROM Reply").executeUpdate();
        entityManager.createQuery("DELETE FROM Vote").executeUpdate();
        
        for (String text: TEXT_LIST) {
            addMoaning(text);
        }
        return "Done.";
    }

    private void addMoaning(String text) {
        Moaning moaning = new Moaning(text);
        moaningRepository.saveMoaning(moaning);
    }
}
